import { marked } from "marked";
import {
    queryparams,
    createAuthHelper,
    MiddlewareCreater,
    Route, RouteItem, RouterDecorator, RouterContext,
    addRoute,
    logger,
    createResponseHelper,
} from "..";

/** 开发一个支持Markdown文件编译的中间件 */
export const app_marked: MiddlewareCreater = {
    name: 'app_marked',
    mode: ['dev', 'build'],
    execute: () => {
        return {
            onSet: async (pathname, data, store) => {
                if (/\.md$/.test(pathname)) {
                    return {
                        data: marked(data?.toString() || ""),
                        originPath: pathname,
                        outputPath: pathname.replace('.md', '.html'),
                    }
                }
                return { data, originPath: pathname, outputPath: pathname }
            },
        }
    }
}


const server_time: RouteItem["handler"] = async (body, ctx) => {
    const data = queryparams(ctx.location.search)
    const post = body && JSON.parse(body.toString())
    return {
        data, post, body,
        time: Date.now()
    }
}

// 路由注册多种方式，以下方法后一种都是对前一种的封装。
// 方式1：直接调用onRoute注册路由，如果要自己处理响应，需要返回false
export const app_system: MiddlewareCreater = {
    name: 'app_system',
    mode: ['dev', 'prod'],
    execute: (conf) => {
        const { handleSuccess, handleError } = createResponseHelper(conf)
        return {
            onRoute: (pathname, ctx) => {
                if (pathname === 'exit') {
                    logger.info("关闭服务器!");
                    setTimeout(() => process.exit(0), 100);
                    handleSuccess(ctx, 'html', "服务器已关闭!".big().bold())
                    return false
                }
            }
        }
    }
}
// 方法2：在中间件中创建route对象注册接口， 路径支持正则表达式
export const app_base: MiddlewareCreater = {
    name: 'app_base',
    // 接口相关定义不适用于 build 模式
    mode: ['dev', 'prod'],
    execute: (conf) => {
        const route = new Route(conf)
        const { getLoginUser } = createAuthHelper(conf.auth || {})

        /** 返回 sse, 支持配置轮询时间 */
        route.on('sse/time', server_time, { type: 'sse' })
        /** 返回普通JSON格式 */
        route.on('server/time', server_time)
        /** 返回普通jsonp格式, 支持callback参数 */
        route.on('server/time.js', server_time, { type: 'jsonp' })

        route.on(/^auth\/loginUser/, (body, ctx) => {
            return {
                user: getLoginUser(ctx),
            }
        })
        return {
            onRoute: route.execute
        }
    }
}

// 方法3：直接注册接口
addRoute('api/time', server_time)
// 方法4：注解方式注册接口
class App {
    /**
     * @demo /api/123/user?callback=jQuery123456789
     */
    @RouterDecorator('api/:id/:name', { type: 'jsonp' })
    api2(body: any, ctx: RouterContext) {
        return ctx.params
    }
}

